package com.xu.cloud.common.advice.exception;

import com.xu.cloud.common.constant.OrderConstant;
import com.xu.cloud.common.exception.ErrorCodeEnum;
import com.xu.cloud.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 数据库异常处理
 *
 * @author xuguan
 * @since 2024/9/4
 */
@Order(OrderConstant.JDK_EXCEPTION_HANDLER_ORDER)
@RestControllerAdvice
@Slf4j
public class JdkExceptionHandlerAdvice {

    /**
     * 配合Spring参数校验工具类{@link org.springframework.util.Assert}使用
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> handlerIllegalArgumentException(IllegalArgumentException illegalArgumentException) {
        log.error("捕获到IllegalArgumentException参数不合法异常, message: ", illegalArgumentException);
        return Result.fail(ErrorCodeEnum.ERR_ILLEGAL_PARAM.getCode(), ErrorCodeEnum.ERR_ILLEGAL_PARAM.getMessage(), null);
    }

    @ExceptionHandler(value = Throwable.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> handlerThrowable(Throwable throwable) {
        log.error("捕获到Throwable异常, message: ", throwable);
        return Result.fail(ErrorCodeEnum.INTERNAL_SERVER_ERROR.getCode(), ErrorCodeEnum.INTERNAL_SERVER_ERROR.getMessage(), null);
    }
}
